package com.mtr.databoard.application.resources;

import com.mtr.databoard.application.EntityResultDto;
import com.mtr.databoard.domain.resources.FileContent;
import com.mtr.databoard.domain.resources.Resource;
import com.mtr.databoard.domain.resources.ResourceManager;
import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("resource")
public class ResourceApplication {


    private ResourceManager resourceManager;

    public ResourceApplication(@Autowired ResourceManager resourceManager) {
        this.resourceManager = resourceManager;
    }


    @GetMapping("/download/{fileId}")
    public void handleFileDownload(@PathVariable(required = false) String fileId, HttpServletResponse response) {
        Resource resource = resourceManager.getResource(fileId);
        FileContent fileContent = resourceManager.getFileContent(fileId);
        if (fileContent != null && fileContent.getContent() != null) {
            //是图片则查看，其它则当作文件下载
            response.setContentType(resource.getType().startsWith("image") ? resource.getType() : "octet-stream");
            response.setHeader("Content-Disposition", ";filename=" + resource.getFileName());

            OutputStream os = null;
            try {
                os = response.getOutputStream();
                os.write(fileContent.getContent().getData());

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    os.close();
                } catch (Exception ex) {

                }
            }


        }

    }


    /**
     * 上传接口
     */
    @PostMapping("/upload")
    @ResponseBody
    public EntityResultDto<List<Resource>> handleFileUpload(HttpServletRequest request) {

        try {

            MultipartHttpServletRequest mpRequest = ((MultipartHttpServletRequest) request);
            Iterator fileNames = mpRequest.getFileNames();

            List<Resource> resources = new ArrayList<>();

            for (Iterator it = fileNames; it.hasNext(); ) {
                String filename = (String) it.next();
                List<MultipartFile> files = mpRequest.getFiles(filename);

                for (MultipartFile file : files
                ) {
                    Resource resource = resourceManager.saveResource(file.getOriginalFilename(), file.getContentType(), new Binary(file.getBytes()));
                    resources.add(resource);

                }

            }

            return EntityResultDto.newSuccessResult(resources);

        } catch (IOException | NoSuchAlgorithmException ex) {
            ex.printStackTrace();
            return EntityResultDto.newErrorResult(null);
        }
    }

    @GetMapping("/temp/{resoueceId}/**")
    @ResponseBody
    public void getComponentResource(@PathVariable String resoueceId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String resourcePath = request.getRequestURI().split(resoueceId.toString())[1];
        resourcePath = URLDecoder.decode(resourcePath, "utf-8");


        Binary content = resourceManager.getFileContent(resoueceId, resourcePath);
        if (content == null) return;

        String fileName = new File(resourcePath).getName();

        response.setContentType("octet-stream");
        response.setHeader("Content-Disposition", ";filename=" + fileName);

        OutputStream os = null;
        try {
            os = response.getOutputStream();
            os.write(content.getData());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception ex) {

            }
        }
    }
}
